
package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.CommodityEntity;
import com.weiqiao.mall.domain.WXCompanyConfEntity;
import com.weiqiao.mall.repository.ICommodityRepository;
import com.weiqiao.mall.service.ICommodityLogService;
import com.weiqiao.mall.service.ICommodityListService;
import com.weiqiao.mall.service.vo.CommodityTypeVO;
import com.weiqiao.modules.monitor.service.RedisService;
import com.weiqiao.utils.*;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商品 产品  配置 业务层实现类,继承BaseWeiXinBizImpl,实现IOrderBiz
 *
 * @author Scott.fan, Sam(佩)
 */
@Service("CommodityListServiceImpl")
public class CommodityListServiceImpl extends BaseWeiXinServiceImpl implements ICommodityListService {

    /**
     * 商品管理数据层
     */
    @Autowired
    private ICommodityRepository commodityRepository;

    @Autowired
    @Qualifier("CommodityLogServiceImpl")
    private ICommodityLogService commodityLogService;

    @Autowired
    private RedisService redisService;

    @Override
    public List<CommodityEntity> findCommoditys(int company_id, Document doc, Pageable pageable) {
        List<CommodityEntity> commodityList = new ArrayList<>();
        List<String> list = commodityRepository.findCommodityByFilterAndPage(company_id, doc, pageable);
        if (!list.isEmpty()) {
            for (String a : list) {
                CommodityEntity c = new Gson().fromJson(a, CommodityEntity.class);
                c.setCreate_date(this.formateTime(c.getCreate_date()));
                commodityList.add(c);
            }
        }
        return commodityList;
    }

    @Override
    public List<CommodityEntity> findCommoditys(int companyId, Bson filter, Bson sort, int limit) {
        List<String> commoditys = commodityRepository.findCommoditySortAndLimit(companyId, filter, sort, limit);
        List<CommodityEntity> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(commoditys)) {
            for (String commodity : commoditys) {
                list.add(new Gson().fromJson(commodity, CommodityEntity.class));
            }
        }
        return list;
    }

    /**
     * 转换时间戳为时间字符串
     */
    public String formateTime(String dateStr) {
        try {
            if (StringUtil.isLong(dateStr)) {
                String date = WeiXinUtils.format(new Date(Long.parseLong(dateStr)), "yyyy-MM-dd HH:mm");
                dateStr = date;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return dateStr;
    }

    @Override
    public CommodityEntity findCommodityById(String commodity_id, int company_id) {
        Bson filter = Filters.and(Filters.eq("commodity_id", commodity_id),
                Filters.eq("company_id", company_id));
        String s = commodityRepository.findCommodityById(company_id, filter);
        return new Gson().fromJson(s, CommodityEntity.class);
    }

    @Override
    public int countCommodity(int companyId, Bson bson) {
        return commodityRepository.countCommodity(companyId, bson);
    }

    @Override
    public boolean updateCommoditys(int companyId, Bson filter, Document doc) {
        return commodityRepository.updateMany(companyId, filter, doc, false);
    }

    @Override
    public List<Map<String, Object>> exportCommodityInfo(int companyId, Bson filter) {
        List<Map<String, Object>> exportContent = new ArrayList<>();
        List<String> list = commodityRepository.findCommoditys(companyId, filter);
        if (list != null && list.size() > 0) {
            for (String str : list) {
                CommodityEntity entity = new Gson().fromJson(str, CommodityEntity.class);
                if (CollectionUtils.isEmpty(entity.getSpecification_details())) {
                    exportContent.add(createExcelContent(entity));
                    continue;
                }
                for (CommodityEntity.SpecificationDetails details : entity.getSpecification_details()) {
                    CommodityEntity entity_spec_detail = new CommodityEntity();
                    BeanUtils.copyProperties(entity, entity_spec_detail);
                    List<CommodityEntity.SpecificationDetails> detailsList = new ArrayList<>();
                    detailsList.add(details);
                    entity_spec_detail.setSpecification_details(detailsList);
                    exportContent.add(createExcelContent(entity_spec_detail));
                }
            }
        }
        return exportContent;
    }

    @Override
    public boolean updateState(int companyId, Bson filter, Document doc) {
        return commodityRepository.updateOneCommodity(companyId, filter, doc, false);
    }

    @Override
    public boolean addCommodity(CommodityEntity commodity) {
        String json = new Gson().toJson(commodity);
        Bson filter1 = Filters.eq("company_id", commodity.getCompany_id());
        Bson filter2 = Filters.eq("commodity_id", commodity.getCommodity_id());
        Bson filter = Filters.and(filter1, filter2);
        // 重新添加商品的时候,清除对应的规格库存
        redisService.hdelete("commodity_inventory" + commodity.getCompany_id(), commodity.getCommodity_id());
        List<CommodityEntity.SpecificationDetails> specification_details = commodity.getSpecification_details();
        if (CollectionUtils.isNotEmpty(specification_details)) {
            for (CommodityEntity.SpecificationDetails entity : specification_details) {
                String key = entity.getFirst_class_id() + entity.getTwo_class_id() + entity.getThree_class_id();
                redisService.hdelete("commodity_specification_inventory" + commodity.getCompany_id(), key);
            }
        }
        return commodityRepository.updateOneCommodityByJson(commodity.getCompany_id(), filter, json);
    }

    @Override
    public List<CommodityEntity> findCommoditys(int companyId, Bson filter) {
        List<CommodityEntity> commodity = new ArrayList<>();
        List<String> list = commodityRepository.findCommoditys(companyId, filter);
        for (String a : list) {
            CommodityEntity c = new Gson().fromJson(a, CommodityEntity.class);
            c.setCreate_date(this.formateTime(c.getCreate_date()));
            commodity.add(c);
        }
        return commodity;
    }

    @Override
    public List<CommodityEntity> findCommodityByVarietyId(int companyId, Bson filter) {
        Gson gson = new Gson();
        List<String> list = commodityRepository.findCommoditys(companyId, filter);
        List<CommodityEntity> comList = new ArrayList<>();
        for (String a : list) {
            CommodityEntity pro = gson.fromJson(a, CommodityEntity.class);
            comList.add(pro);
        }
        return comList;
    }

    @Override
    public Pageable pageSort(HttpServletRequest request, Pageable pageable) {
        //价格,销量排序
        String price = request.getParameter("price");
        String sale = request.getParameter("sale");
        Sort sort = pageable.getSort();
        if (!StringUtil.isBlank(price) && StringUtil.isBlank(sale)) {
            if ("ASC".equals(price)) {
                sort = Sort.by(Sort.Direction.ASC, "vip_price");
            } else {
                sort = Sort.by(Sort.Direction.DESC, "vip_price");
            }
        }
        if (!StringUtil.isBlank(sale) && StringUtil.isBlank(price)) {
            if ("ASC".equals(sale)) {
                sort = Sort.by(Sort.Direction.ASC, "deal_times");
            } else {
                sort = Sort.by(Sort.Direction.DESC, "deal_times");
            }
        }
        // 多条件排序
        if (!StringUtil.isBlank(sale) && !StringUtil.isBlank(price)) {
            if ("ASC".equals(sale) && "ASC".equals(price)) {
                sort = new Sort(Sort.Direction.ASC, "vip_price").
                        and(new Sort(Sort.Direction.ASC, "deal_times"));
            }
            if ("ASC".equals(sale) && "DESC".equals(price)) {
                sort = new Sort(Sort.Direction.DESC, "vip_price").
                        and(new Sort(Sort.Direction.ASC, "deal_times"));
            }
            if ("DESC".equals(sale) && "DESC".equals(price)) {
                sort = new Sort(Sort.Direction.DESC, "vip_price").
                        and(new Sort(Sort.Direction.DESC, "deal_times"));
            }
            if ("DESC".equals(sale) && "ASC".equals(price)) {
                sort = new Sort(Sort.Direction.ASC, "vip_price").
                        and(new Sort(Sort.Direction.DESC, "deal_times"));
            }
        }
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        return pageable;
    }

    @Override
    public Map deleteById(HttpServletRequest request) {
        //公司id,商品id
        int company_id = MallUtil.getCompanyId(request);
        String commodity_id = request.getParameter("commodity_id");
        Map map = new HashMap(2);
        if (StringUtils.isBlank(commodity_id) || company_id == 0) {
            map.put("result", false);
            map.put("msg", "没有数据删除");
            return map;
        }
        CommodityEntity entity = this.findCommodityById(commodity_id, company_id);
        if (entity == null || entity.getState() == 0) {
            map.put("result", false);
            map.put("msg", "没有此商品或已上架");
            return map;
        }
        if (entity.getDelete_flag() == 1) {
            map.put("result", false);
            map.put("msg", "此商品已被删除");
            return map;
        }
        Bson filter = Filters.and(Filters.eq("company_id", company_id), Filters.eq("commodity_id", commodity_id));
        Document doc = new Document();
        doc.append("delete_flag", 1);
        doc.append("state", 1);
        boolean flag = this.updateState(company_id, filter, doc);
        if (!flag) {
            map.put("result", false);
            map.put("msg", "此商品已被删除");
            return map;
        }
        //商品操作流水添加
        commodityLogService.addCommodityLog(company_id, entity, 13);
        map.put("result", true);
        map.put("msg", "删除成功");
        return map;
    }

    @Override
    public Map createQrcode(HttpServletRequest request, WXCompanyConfEntity companyConf) {
        String url = "";
        long userid = SecurityUtils.getUserId();
        //商品id
        String proid = request.getParameter("proid");
        //公司id,商品id
        int company_id = MallUtil.getCompanyId(request);
        String real = request.getSession().getServletContext().getRealPath("");
        String splicing = "giftCard" + File.separator;
        if (!StringUtil.isBlank(companyConf) && !StringUtil.isBlank(companyConf.getSmallappid())
                && !StringUtil.isBlank(companyConf.getSecret())) {
            String token = SmallAppUtil.getToken(companyConf.getSmallappid(), companyConf.getSecret());
            if (!StringUtil.isBlank(token)) {
                url = SmallAppUtil.getGiftQRCode(token, real + splicing,
                        "pages/index/index?proid=" + proid + "&userid=" + userid);
            }
        }
        //把生成的二维码放到商品上
        if (!org.apache.commons.lang.StringUtils.isBlank(url)) {
            Bson filter = Filters.eq("commodity_id", proid);
            Document doc = new Document();
            doc.append("qrcode_url", url);
            this.updateState(company_id, filter, doc);
        }
        Map map = new HashMap(1);
        map.put("content", url);
        return map;
    }

    @Override
    public Map deleteVariety(CommodityTypeVO commodityTypeVO) {
        //一级分类id
        Map resultMap = new HashMap(2);
        if (StringUtil.isBlank(commodityTypeVO.getVariety_id()) &&
                StringUtil.isBlank(commodityTypeVO.getSecond_variety_id())) {
            resultMap.put("result", false);
            resultMap.put("msg", "没有数据删除");
            return resultMap;
        }
        List<CommodityEntity> list = new ArrayList<>();
        // 判断是删除一级分类还是二级分类
        if (!StringUtil.isBlank(commodityTypeVO.getVariety_id()) &&
                StringUtil.isBlank(commodityTypeVO.getSecond_variety_id())) {
            Document document = new Document();
            document.append("delete_flag", 0);
            document.append("state", 0);
            document.append("variety_id", commodityTypeVO.getVariety_id());
            document.append("company_id", commodityTypeVO.getCompany_id());
            list = this.findCommodityByVarietyId(commodityTypeVO.getCompany_id(), document);
        }
        if (StringUtil.isBlank(commodityTypeVO.getVariety_id()) &&
                !StringUtil.isBlank(commodityTypeVO.getSecond_variety_id())) {
            Document document = new Document();
            document.append("second_variety_id", commodityTypeVO.getSecond_variety_id());
            document.append("company_id", commodityTypeVO.getCompany_id());
            list = this.findCommodityByVarietyId(commodityTypeVO.getCompany_id(), document);
        }
        //判断该分类是否有关联商品
        if (list.size() == 0) {
            resultMap.put("result", true);
            resultMap.put("msg", "可以删除");
            return resultMap;
        }
        resultMap.put("result", false);
        resultMap.put("msg", "删除失败！请清除该分类下的商品");
        return resultMap;
    }

    /**
     * excel 内容组装
     *
     * @param entity 商品信息
     */
    public Map<String, Object> createExcelContent(CommodityEntity entity) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String create_date = simpleDateFormat.format(Long.parseLong(entity.getCreate_date()));
        Map map = new LinkedHashMap();
        map.put("商品id", entity.getCommodity_id());
        map.put("商品编号", entity.getUnion_code());
        map.put("商品名称", entity.getName());
        map.put("专柜价格", entity.getPrice());
        map.put("成本价格", entity.getCost_price());
        map.put("会员价格", entity.getVip_price());
        map.put("库存", entity.getInventory());
        map.put("状态", entity.getState() == 0 ? "已上架" : "仓库中");
        map.put("交易次数", entity.getDeal_times());
        map.put("累计评价次数", entity.getComment_times());
        map.put("供应商", entity.getSupplier_name());
        map.put("创建时间", create_date);
        StringBuilder buffer = null;
        // 规格明细，规格值
        List<CommodityEntity.SpecificationDetails> list = entity.getSpecification_details();
        if (CollectionUtils.isNotEmpty(list)) {
            buffer = new StringBuilder();
            // 获取眉头信息
            buffer.append("页码");
            for (CommodityEntity.Specifications info : entity.getSpecifications()) {
                buffer.append("     "+info.getName());
            }
            buffer.append("     "+"价格");
            buffer.append("     "+"库存");
            buffer.append("     "+"佣金");
            buffer.append("\n");
            // 获取内容
            int count = 1;
            for (int i = 0; i < list.size(); i++) {
                CommodityEntity.SpecificationDetails specificationDetails = list.get(i);
                if (!StringUtil.isBlank(specificationDetails.getFirst_class_value()) || !StringUtil.isBlank(specificationDetails.getTwo_class_value())
                        || !StringUtil.isBlank(specificationDetails.getThree_class_value())) {
                    buffer.append(count );
                    if (!StringUtil.isBlank(specificationDetails.getFirst_class_value())) {
                        buffer.append("     "+specificationDetails.getFirst_class_value());
                    }
                    if (!StringUtil.isBlank(specificationDetails.getTwo_class_value())) {
                        buffer.append("     " + specificationDetails.getTwo_class_value());
                    }
                    if (!StringUtil.isBlank(specificationDetails.getThree_class_value())) {
                        buffer.append("     " + specificationDetails.getThree_class_value());
                    }
                    buffer.append("     " + specificationDetails.getVip_price());
                    buffer.append("     " + specificationDetails.getInventory());
                    buffer.append("     " + specificationDetails.getCommission());
                    buffer.append("\n");
                    count++;
                }
            }
        }
        map.put("规格值", buffer);
        return map;
    }

    @Override
    public CommodityEntity getLatestCommodity(HttpServletRequest request) {
        // 获取当前公司最后一条商品信息,通过倒序,取一条的方式获取
        String company_id = request.getParameter("company_id");
        int companyId = StringUtils.isInteger(company_id) ? Integer.valueOf(company_id) : 0;
        Bson filter = Filters.and(Filters.eq("company_id", companyId), Filters.eq("delete_flag", 0));
        Bson sort = Filters.eq("create_date", -1);
        List<String> list = commodityRepository.findCommoditySortAndLimit(companyId, filter, sort, 1);
        CommodityEntity entity;
        if (!list.isEmpty()) {
            entity = new Gson().fromJson(list.get(0), CommodityEntity.class);
        } else {
            entity = new CommodityEntity();
        }
        return entity;
    }

}
